package com.ruoyi.wechat.config;

import com.ruoyi.wechat.service.IOrderService;
import lombok.Getter;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 延时订单
 * </p>
 *
 * @author YinHeng
 * @since 2024/4/9
 */
@Getter
public class DelayedOrder implements Delayed {

    private final String tradeNo;
    private final long expireTimeMillis; // 订单超时时间戳（毫秒）
    private IOrderService orderService;

    public DelayedOrder(IOrderService orderService, String tradeNo, long delayInSeconds) {
        this.tradeNo = tradeNo;
        // 设置订单在当前时间多少秒后超时
        this.expireTimeMillis = System.currentTimeMillis() + delayInSeconds;
        this.orderService = orderService;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long remainingNanos = expireTimeMillis - System.currentTimeMillis();
        return unit.convert(remainingNanos, TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        if (other == this) {
            return 0;
        }
        DelayedOrder t = (DelayedOrder) other;
        long d = (getDelay(TimeUnit.MILLISECONDS) - t.getDelay(TimeUnit.MILLISECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

    // 其他订单属性及方法...

    // 处理订单取消的逻辑
    public void cancelOrder() {
        orderService.canCel(this.tradeNo);
        // 在这里调用实际的服务接口或方法取消订单
    }
}